#coding:utf-8
"""
*   TG_Coder : Dzlua
*   Email    : 505544956@qq.com
*   Time     : 2017/09/07
"""
#--------------------#
from flask import jsonify, make_response, url_for, request, render_template, g, abort
from flask_restful import reqparse, Resource, Api
from flask_httpauth import HTTPBasicAuth
from flask_sqlalchemy import SQLAlchemy
from passlib.apps import custom_app_context as pwd_context
from itsdangerous import (TimedJSONWebSignatureSerializer
                          as Serializer, BadSignature, SignatureExpired)
import socket, json, re

#--------------------#
db = SQLAlchemy()
auth = HTTPBasicAuth()
#--------------------#
def req_prots(host, port, cmd):
    data = {'host': host, 'port': port, 'cmd': cmd}
    try:
        sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sk.connect((host, port))
        sk.sendall(cmd)
        data['res'] = sk.recv(65536)
        sk.close()
        return (0, data)
    except:
        return (-1, data)
#--------------------#
def make_res(code, args=None, msg=None):
    text = ''
    if code==0:
        text = 'ok'
    elif code==-1:
        text = '[Protocol] ERROR req_prots.'
    elif code==1:
        text = 'The user already exists.'
    elif code==2:
        text = 'The user not exists.'
    elif code==3:
        pass
    return {'status': code, 'msg': msg or text, 'data': args}
#--------------------#
def js_str_to_dict(js_str, err_replace_data):
    try:
        return json.loads(js_str, strict=False)
    except:
        return err_replace_data
#--------------------#
